
package com.rentong.common;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * @author zxy
 * @ClassName: DateUtils
 * @Description: 日期工具类
 * @date 2016年4月19日 下午3:44:16
 */
public class DateUtils {
    private static final Logger LOG = LoggerFactory.getLogger(DateUtils.class);

    public static String format_ymd = "yyyy-MM-dd";
    public static String format_ymd_hms = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH", "yyyy-MM-dd", "yyyy-MM",
            "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH", "yyyy/MM/dd", "yyyy/MM", "yyyy.MM.dd HH:mm:ss",
            "yyyy.MM.dd HH:mm", "yyyy.MM.dd HH", "yyyy.MM.dd", "yyyy.MM"};

    /**
     * 格式化某一时间字符串
     *
     * @param date
     * @param format
     * @return Date
     */
    public static Date getDate(String date, String format) {
        SimpleDateFormat sp = new SimpleDateFormat(format);
        try {
            if (date != null) {
                return sp.parse(date);
            }
            return null;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String formatDate(Date date) {
        return formatDate(date, null);
    }

    /**
     * @param date    日期
     * @param pattern 模版
     * @return 日期字符串
     * @Description: 日期转换成字符串
     */
    public static String formatDate(Date date, String pattern) {
        if (pattern == null) {
            pattern = format_ymd;
        }

        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern(pattern);
        return sdf.format(date);
    }

    /**
     * @param date 日期
     * @return 时间日期字符串
     * @Description: 将字符串转换成时间日期
     */
    public static String formatDateTime(Date date) {
        return formatDate(date, format_ymd_hms);
    }

    /**
     * @param str     日期字符串
     * @param pattern 模版
     * @return 日期
     * @Description: 将字符串转换成日期
     */
    public static Date parseDate(String str, String pattern) {
        if (StringUtils.isBlank(pattern)) {
            pattern = format_ymd;
        }
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern(pattern);
        try {
            return sdf.parse(str);
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * @return 日期字符串
     * @Description: 获取当前日期
     */
    public static String getDate() {
        return getDate(format_ymd);
    }

    /**
     * @param pattern 模版
     * @return 日期字符串
     * @Description: 获取当前日期
     */
    public static String getDate(String pattern) {
        return formatDate(new Date(), pattern);
    }

    /**
     * @return 时间字符串
     * @Description: 获取当前时间
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }

    /**
     * @return 时间日期字符串
     * @Description: 获取当前时间日期
     */
    public static String getDateTime() {
        return formatDate(new Date(), format_ymd_hms);
    }

    /**
     * @return
     * @Description: 获取当前时间日期, 毫秒
     */
    public static long getMilliSecond() {
        return Long.parseLong(formatDate(new Date(), "yyyyMMddHHmmssSSS"));
    }

    public static String getMilliSecondStr() {
        return formatDate(new Date(), "yyyyMMddHHmmssSSS");
    }

    public static String getMilliSecondStr(String fmd) {
        return formatDate(new Date(), fmd);
    }

    /**
     * @return 年份字符串
     * @Description: 获取当前年份
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * @return 月份字符串
     * @Description: 获取当前月份
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * @return 日字符串
     * @Description: 获取当前日
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * @return 周字符串
     * @Description: 获取当前周
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    /**
     * @return
     * @Description: 获取昨天
     */
    public static Date getYesterday() {
        return getYesterday(new Date());
    }

    /**
     * @param date
     * @return
     * @Description: 获取昨天
     */
    public static Date getYesterday(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTime();
    }

    /**
     * @return
     * @Description: 获取明天
     */
    public static Date getTomorrow() {
        return getTomorrow(new Date());
    }

    /**
     * @return
     * @Description: 获取明天
     */
    public static Date getTomorrow(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    /**
     * @param date
     * @return
     * @Description: 获取过去的时间
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (24 * 60 * 60 * 1000);
    }

    /**
     * @param date
     * @return
     * @Description: 获取过去的小时
     */
    public static long pastHour(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 60 * 1000);
    }

    /**
     * @param date
     * @return
     * @Description: 获取过去的分钟
     */
    public static long pastMinutes(Date date) {
        long t = new Date().getTime() - date.getTime();
        return t / (60 * 1000);
    }

    /**
     * @param timeMillis
     * @return
     * @Description: 转换为时间（天,时:分:秒.毫秒）
     */
    public static String formatDateTime(long timeMillis) {
        long day = timeMillis / (24 * 60 * 60 * 1000);
        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
    }

    /**
     * @param before
     * @param after
     * @return
     * @Description: 获取两个日期之间的天数
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (double) (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
    }

    /**
     * 获取当天日期从零点开始
     *
     * @return
     */
    public static String getDateZeroTime() {
        return formatDate(new Date(getZeroTime()), format_ymd_hms);
    }

    /**
     * 获取当天日期开始时间 如：2016-05-27 00:00:00
     *
     * @return
     */
    public static long getZeroTime() {
        long current = System.currentTimeMillis();//当前时间毫秒数
        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
        return zero;
    }

    /**
     * 时间比较
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return startTime大于endTime 返回-1 ,小于返回1，相等返回0
     */
    public static int compareDate(String startTime, String endTime) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dt1 = df.parse(startTime);
            Date dt2 = df.parse(endTime);
            if (dt1.getTime() > dt2.getTime()) {
                return -1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception ex) {
            LOG.error("compareDate parse is error...", ex);
        }
        return 0;
    }

    /**
     * 返回第几个月份，不是几月
     * 季度一年四季， 第一季度：2月-4月， 第二季度：5月-7月， 第三季度：8月-10月， 第四季度：11月-1月
     */
    public static int getQuarterInMonth(int month, boolean isQuarterStart) {
        int months[] = {1, 4, 7, 10};
        if (!isQuarterStart) {
            months = new int[]{3, 6, 9, 12};
        }
        if (month >= 2 && month <= 4)
            return months[0];
        else if (month >= 5 && month <= 7)
            return months[1];
        else if (month >= 8 && month <= 10)
            return months[2];
        else
            return months[3];
    }

    /**
     * 获取当天的开始时间
     */
    public static Date getTodayBegin() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取本月的开始时间
     */
    public static Date getBeginDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        return calendar.getTime();
    }

    /**
     * 获取本月的结束时间
     */
    public static Date getEndDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), day, 23, 59, 59);
        return calendar.getTime();
    }

    /**
     * 获取本季度的开始时间
     */
    public static Date getBeginDayOfThisQuarter() {
        Calendar calendar = new GregorianCalendar();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        calendar.setTime(new Date());
        gc.setTime(new Date());
        int month = getQuarterInMonth(Integer.valueOf(gc.get(2) + 1), true);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    /**
     * 获取本年的开始时间
     */
    public static Date getBeginDayOfThisYear() {
        Calendar calendar = new GregorianCalendar();
        int year = Calendar.getInstance().get(1);
        calendar.set(year, 1, 1, 0, 0, 0);
        return calendar.getTime();
    }

    /**
     * 获取该日期的最后一刻
     */
    public static Date getDateEnd(String str, String pattern) {
        Date date = DateUtils.parseDate(str, pattern);
        if (date == null)
            return null;
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

}
